package com.iman.fetion.mina;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.IoFilter.NextFilter;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.util.SessionLog;

public class FetionLoggingFilter extends LoggingFilter {

	public void messageReceived(NextFilter nextFilter, IoSession session,
			Object message) {

		ByteBuffer rb = (ByteBuffer) message;
		StringBuffer buff = new StringBuffer();
		String msg = null;
		try {
			if (SessionLog.isInfoEnabled(session)) {
				SessionLog.info(session, "RECEIVED: " + message);
				ByteBuffer wb = ByteBuffer.allocate(rb.remaining());
				wb.put(rb);
				wb.flip();
				while (wb.hasRemaining()) {
					buff.append((char) wb.get());
				}
				msg = new String(wb.array(), "utf-8");
				System.out.println("Reveiced-FetionLoggingFilter:" + msg);
				if (buff.toString().startsWith("<policy-file-request/>")) {
					String xml = "<cross-domain-policy>";
					xml += "<allow-access-from domain=\"*\" to-ports=\"*\" />";
					xml += "<allow-access-from domain=\"*\"/>";
					xml += "</cross-domain-policy>";
					session.write(xml + "\0");
					System.out.println("Response the policy file to client...");
					session.close();
					return;
				}
			}

			ByteBuffer abb = ByteBuffer.wrap(msg.getBytes("utf-8"));
			System.out.println("Reveiced-nextFilter-message:" + abb);
			nextFilter.messageReceived(session, abb);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void messageSent(NextFilter nextFilter, IoSession session,
			Object message) {
		if (SessionLog.isInfoEnabled(session)) {
			SessionLog.info(session, "SENT-FetionLoggingFilter: " + message);
			ByteBuffer buf = (ByteBuffer) message;
			StringBuffer buff = new StringBuffer();
			while (buf.hasRemaining()) {
				buff.append((char) buf.get());
			}
			System.out.println("Sent:" + buff.toString());
		}
		nextFilter.messageSent(session, message);
	}
}
